package MultiThread;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorTest {

    public static void main(String[] args) throws InterruptedException {
        dynamicModifyExecutor();
    }

    public static void dynamicModifyExecutor() throws InterruptedException {
        ThreadPoolExecutor executor = buildThreadPoolExecutor();
        for (int i = 0; i < 15; i++) {
            int index = i;
            executor.submit(()->{
                threadPoolStatus(executor, "创建阶段"+index);
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPoolStatus(executor, "----------------改变之前----------------");
        executor.setMaximumPoolSize(10);
        executor.setCorePoolSize(10);

        threadPoolStatus(executor, "----------------改变之后----------------");
        Thread.currentThread().join();
    }

    private static void threadPoolStatus(ThreadPoolExecutor executor, String name) {
        LinkedBlockingQueue queue = (LinkedBlockingQueue) executor.getQueue();
        System.out.println(Thread.currentThread().getName() + "\n-" + name + "-:" +
                " 核心线程数: "+ executor.getCorePoolSize() +
                " 活动线程数: "+ executor.getActiveCount() +
                " 最大线程数: "+ executor.getMaximumPoolSize() +
                " 线程池活跃度: "+ divide(executor.getActiveCount(), executor.getMaximumPoolSize()) +
                " 任务完成数 " + executor.getCompletedTaskCount() +
                " 队列大小 " + (queue.size() + queue.remainingCapacity()) +
                " 当前排队数 " + queue.size() +
                " 队列剩余大小 " + queue.remainingCapacity() +
                " 队列实用度 " + divide(queue.size(), queue.size()+ queue.remainingCapacity())
                );
    }

    private static String divide(int activeCount, int maximumPoolSize) {
        return String.format("%1.2f%%", Double.parseDouble(activeCount+"") / Double.parseDouble(maximumPoolSize+"")*100);
    }

    private static ThreadPoolExecutor buildThreadPoolExecutor() {
        return new ThreadPoolExecutor(2,5,60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10));
    }
}
